package com.drinks.yiniang.ui.activity.user.setting;

import android.annotation.TargetApi;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.TextView;

import com.drinks.yiniang.R;
import com.drinks.yiniang.common.help.LogoutHelp;
import com.drinks.yiniang.entity.common.StringJson;
import com.drinks.yiniang.entity.common.UpdateVersionJson;
import com.drinks.yiniang.io.api.CommonApiIO;
import com.drinks.yiniang.io.api.LoginApiIO;
import com.drinks.yiniang.io.service.DownloadService;
import com.drinks.yiniang.ui.activity.common.WebActivity;
import com.drinks.yiniang.ui.activity.user.UserDataActivity;
import com.drinks.yiniang.ui.activity.user.address.DeliverAddressActivity;
import com.drinks.yiniang.utils.FileUtils;
import com.drinks.yiniang.utils.GlideCatchUtil;
import com.drinks.yiniang.utils.ToastUtils;
import com.drinks.yiniang.utils.VersionUtils;
import com.hansen.library.Constants;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.listener.OnSureCancelListener;
import com.hansen.library.ui.widget.dialog.ActionSheetDialog;
import com.hansen.library.ui.widget.dialog.MaterialDialog;
import com.hansen.library.ui.widget.textview.BorderTextView;
import com.hansen.library.ui.activity.BaseTranBarActivity;
import com.hansen.library.listener.OnNavgationBarClickListener;
import com.hansen.library.ui.widget.nav.NavigationBarLayout;
import com.hansen.library.utils.StringUtils;

/**
 * 设置页面
 *
 * @author han
 * @date 2019/09/06
 */
public class UserSettingActivity extends BaseTranBarActivity implements OnNavgationBarClickListener, OnSureCancelListener {

    private final int REQ_USER_DATA_CODE = 0x01;
    private static final int REQ_INSTALL_PERMISSION = 0x02;

    private final int MSG_GET_CACHE = 0x01;
    private final int MSG_CLEAR_CACHE = 0x02;

    private final int TYPE_UPDATE_DIALOG = 0x01;//更新dialog
    private final int TYPE_PERMISSION_DIALOG = 0x02;//安装未知应用权限dialog

    //nav
    private NavigationBarLayout nav_bar_user_setting;
    //支付设置
    private BorderTextView tv_setting_pay_setting;
    //个人设置
    private BorderTextView tv_setting_personal_setting;
    //收货地址
    private BorderTextView tv_setting_deliver_address;
    //评价我们
    private BorderTextView tv_setting_evaluated_us;
    //清除缓存
    private BorderTextView tv_setting_clear_cache;
    //检测更新
    private BorderTextView tv_setting_check_update;
    //关于我们
    private BorderTextView tv_setting_about_us;
    //申请厂商专区
    private BorderTextView tv_setting_apply_area;
    //大宗采购
    private BorderTextView tv_setting_purchase;
    //退出登录
    private TextView tv_setting_logout;

    //更新提示
    private MaterialDialog mUpdateVersionDialog;

    //新版版本名称
    private String mVersionName;
    //新版下载地址
    private String mDownloadUrl;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_GET_CACHE:
                    //pbar_clear_cache.setVisibility(View.GONE);
                    //tv_setting_clear_cache.setText((String)msg.obj);
                    break;
                case MSG_CLEAR_CACHE:
                    if ((boolean) msg.obj) {
                        ToastUtils.showShort("已清除缓存");
                        getGlideCache();
                    } else {
                        ToastUtils.showShort("清除失败");
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void initView() {
        nav_bar_user_setting = findViewById(R.id.nav_bar_user_setting);

        tv_setting_pay_setting = findViewById(R.id.tv_setting_pay_setting);
        tv_setting_personal_setting = findViewById(R.id.tv_setting_personal_setting);
        tv_setting_deliver_address = findViewById(R.id.tv_setting_deliver_address);
        tv_setting_evaluated_us = findViewById(R.id.tv_setting_evaluated_us);
        tv_setting_clear_cache = findViewById(R.id.tv_setting_clear_cache);
        tv_setting_check_update = findViewById(R.id.tv_setting_check_update);
        tv_setting_about_us = findViewById(R.id.tv_setting_about_us);
        tv_setting_apply_area = findViewById(R.id.tv_setting_apply_area);
        tv_setting_purchase = findViewById(R.id.tv_setting_purchase);

        tv_setting_logout = findViewById(R.id.tv_setting_logout);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mContext = this;
    }

    @Override
    protected void initListener() {
        nav_bar_user_setting.setOnNavgationBarClickListener(this);
        tv_setting_pay_setting.setOnClickListener(this);
        tv_setting_personal_setting.setOnClickListener(this);
        tv_setting_deliver_address.setOnClickListener(this);
        tv_setting_evaluated_us.setOnClickListener(this);
        tv_setting_clear_cache.setOnClickListener(this);
        tv_setting_check_update.setOnClickListener(this);
        tv_setting_about_us.setOnClickListener(this);
        tv_setting_apply_area.setOnClickListener(this);
        tv_setting_purchase.setOnClickListener(this);
        tv_setting_logout.setOnClickListener(this);
    }

    @Override
    public void widgetClick(View v) {
        Intent mIntent;

        switch (v.getId()) {
            case R.id.tv_setting_pay_setting://支付设置
                mIntent = new Intent(mContext, PaymentSettingActivity.class);
                startActivity(mIntent);
                break;
            case R.id.tv_setting_personal_setting://个人设置
                mIntent = new Intent(mContext, UserDataActivity.class);
                startActivityForResult(mIntent, REQ_USER_DATA_CODE);
                break;
            case R.id.tv_setting_deliver_address://收货地址
                mIntent = new Intent(mContext, DeliverAddressActivity.class);
                startActivity(mIntent);
                break;
            case R.id.tv_setting_evaluated_us://评价我们
                ToastUtils.showShort(R.string.text_to_apps_marketplace_evaluate);
                break;
            case R.id.tv_setting_clear_cache://清除缓存
                clearCacheDialog();
                break;
            case R.id.tv_setting_check_update://检测更新
                checkVersion();
                break;
            case R.id.tv_setting_about_us://关于我们
                mIntent = new Intent(mContext, WebActivity.class);
                mIntent.putExtra(Constants.KeyType, WebActivity.WEB_TYPE_ABOUT_US);
                startActivity(mIntent);
                break;
            case R.id.tv_setting_apply_area://申请厂商专区
                mIntent = new Intent(mContext, WebActivity.class);
                mIntent.putExtra(Constants.KeyType, WebActivity.WEB_TYPE_APPLY_MFRS_AREA);
                startActivity(mIntent);
                break;
            case R.id.tv_setting_purchase://大宗采购
                mIntent = new Intent(mContext, WebActivity.class);
                mIntent.putExtra(Constants.KeyType, WebActivity.WEB_TYPE_BIG_PURCHASE);
                startActivity(mIntent);
                break;
            case R.id.tv_setting_logout://退出登录
                doLogout();
                break;
            default:
                break;
        }
    }

    @Override
    public int getTranBarResID() {
        return R.layout.activity_user_setting;
    }

    @Override
    public void onBackClick(View v) {
        finish();
    }

    @Override
    public void onEditClick(View v) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQ_INSTALL_PERMISSION) {//以防万一，再次检查权限
            if (checkInstallApkPermission()) {//有权限
                startDownloadApkService();
            }
        }
    }

    @Override
    public void onSure(int type, String value) {
        switch (type) {
            case TYPE_UPDATE_DIALOG://下载更新
                if (checkInstallApkPermission()) {//有权限
                    startDownloadApkService();
                }
                break;
            case TYPE_PERMISSION_DIALOG://权限
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    toInStallPermissionSettingActivity();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onCancel(int type) {
        mVersionName = null;
        mDownloadUrl = null;
        if (TYPE_PERMISSION_DIALOG == type) {
            ToastUtils.showShort(getString(R.string.text_refund_install_permission));
        }
    }

    private void clearCacheDialog() {
        new ActionSheetDialog(mContext)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("清除缓存", ActionSheetDialog.SheetItemColor.Black,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                clearGlideCache();
                            }
                        }).show();
    }

    private void getGlideCache() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();

                message.what = MSG_GET_CACHE;
                message.obj = GlideCatchUtil.getInstance().getCacheSize();

                mHandler.sendMessage(message);
            }
        }).start();
    }

    private void clearGlideCache() {
        //清除内存缓存
        GlideCatchUtil.getInstance().clearCacheMemory();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();

                message.what = MSG_CLEAR_CACHE;
                //清除磁盘缓存
                message.obj = GlideCatchUtil.getInstance().clearCacheDiskSelf();

                mHandler.sendMessage(message);
            }
        }).start();
    }

    //退出登录
    private void doLogout() {
        new ActionSheetDialog(mContext)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem(getString(R.string.text_logout_the_current_account), ActionSheetDialog.SheetItemColor.Black,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                doLogoutApi();
                            }
                        }).show();
    }

    private void doLogoutApi() {
        showLoadingDialog();

        LoginApiIO.getInstance().doLogout(new APIRequestCallback<StringJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(StringJson res) {
                LogoutHelp.doLogout(true);
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //版本检测
    private void checkVersion() {
        showLoadingDialog();

        CommonApiIO.getInstance().doAppUpdate(VersionUtils.getVersionCode(), new APIRequestCallback<UpdateVersionJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(UpdateVersionJson res) {
                if (res.getData().isNeed_update() && res.getData().getVersion_info() != null) {//需要更新
                    mVersionName = res.getData().getVersion_info().getVersion_name();
                    mDownloadUrl = res.getData().getVersion_info().getDownload_url();

                    initUpdateVersionDialog(TYPE_UPDATE_DIALOG, null, getString(R.string.text_update_app_tips), Constants.TAG_TIPS_DIALOG);
                } else {
                    ToastUtils.showShort(getString(R.string.text_version_is_new));
                }
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    private void startDownloadApkService() {
        if (!StringUtils.isHttp(mDownloadUrl)) {
            ToastUtils.showShort(getString(R.string.text_error_download_url));
            return;
        }

        Intent intent = new Intent(mContext, DownloadService.class);
        intent.putExtra(Constants.KeyUrl, mDownloadUrl);
        intent.putExtra(Constants.KeyName, mVersionName);
        startService(intent);
    }

    //更新版本或权限提示
    private void initUpdateVersionDialog(int type, String title, String content, String tag) {
        if (mVersionName != null && StringUtils.isHttp(mDownloadUrl)) {
            mUpdateVersionDialog = MaterialDialog.newInstance(type, title, content);

            mUpdateVersionDialog.show(getSupportFragmentManager(), tag);
        }
    }

    private boolean checkInstallApkPermission() {
        if (!FileUtils.checkInstallPakPermission(mContext)) {
            initUpdateVersionDialog(TYPE_PERMISSION_DIALOG, getString(R.string.text_open_install_permission), getString(R.string.text_install_unkonw_apk_permission), Constants.TAG_TIPS_PERMISSION);
            return false;
        }

        return true;
    }

    @TargetApi(android.os.Build.VERSION_CODES.O)
    private void toInStallPermissionSettingActivity() {
        Uri packageURI = Uri.parse("package:" + getPackageName());
        //注意这个是8.0新API
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        startActivityForResult(intent, REQ_INSTALL_PERMISSION);
    }
}
